package com.sunxiansheng.user.excel;

import com.sunxiansheng.tool.excel.EasyExcelExporter;
import com.sunxiansheng.user.entity.po.SysUserPo;
import com.sunxiansheng.user.mapper.SysUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserExcelExport {

    @Resource
    private SysUserMapper sysUserMapper;

    public void exportExcel() {
        // 构造查询条件
        SysUserPo sysUserPo = new SysUserPo();
        sysUserPo.setName("sun");
        // 创建导出器
        EasyExcelExporter exporter = new EasyExcelExporter.Builder<excelEntity>(
                // 从db中查询记录总条数
                () -> {
                    Integer count = sysUserMapper.count(sysUserPo);
                    return count.longValue();
                },
                (pageIndex, pageSize) -> {
                    // 从db中查询记录并封装成excelEntity
                    List<SysUserPo> sysUserPos = sysUserMapper.queryPage(sysUserPo, pageIndex, pageSize);
                    // 转换为entity
                    List<excelEntity> collect = sysUserPos.stream().map(
                            po -> {
                                excelEntity excelEntity = new excelEntity();
                                excelEntity.setId(po.getId());
                                excelEntity.setName(po.getName());
                                return excelEntity;
                            }
                    ).collect(Collectors.toList());
                    return collect;
                }
            ).sheetDataRows(4L)
                .writeDataRows(2L)
                .excelHead(Arrays.asList("ID", "NAME"))
                .build();
        // 导出Excel
        exporter.exportExcel("test");
    }

}